/* eslint-disable no-param-reassign */
import {
  CodeListItem,
  getWFContext,
  GridController,
  GridFieldColumnController,
  GridRowState,
  IColumnState,
  IModalData,
  OpenAppViewCommand,
} from '@ibiz-template/runtime';
import dayjs from 'dayjs';
import { IDEGridFieldColumn } from '@ibiz/model-core';
import { ModelError } from '@ibiz-template/core';
import { clone } from 'ramda';
import { ICheckinMonthGridState } from './i-checkin-month-grid.state';

export class CheckinMonthGridController extends GridController {
  declare state: ICheckinMonthGridState;

  /**
   * @description 星期
   * @type {string[]}
   * @memberof CheckinMonthGridController
   */
  public weekDays: string[] = [
    '星期日',
    '星期一',
    '星期二',
    '星期三',
    '星期四',
    '星期五',
    '星期六',
  ];

  /**
   * @description 开始属性
   * @type {string}
   * @memberof CheckinMonthGridController
   */
  public startField: string = '';

  /**
   * @description 结束属性
   * @type {string}
   * @memberof CheckinMonthGridController
   */
  public endField: string = '';

  /**
   * @description 分组列属性
   * @type {string}
   * @memberof CheckinMonthGridController
   */
  public groupColumnField: string = '';

  /**
   * @description 考勤申请类型
   * @type {readonly}
   * @memberof CheckinMonthGridController
   */
  public attendanceTypes: readonly CodeListItem[] = [];

  /**
   * @description 考勤代码表标识
   * @protected
   * @type {string}
   * @memberof CheckinMonthGridController
   */
  protected attendCodeListTag: string = 'Attendance_type';

  /**
   * @description 自定义列状态
   * @type {IColumnState[]}
   * @memberof CheckinMonthGridController
   */
  public customColumnStates: IColumnState[] = [];

  protected async onCreated(): Promise<void> {
    await super.onCreated();
    const { startfield, endfield, groupcolumnfield, attendcodelisttag } =
      this.controlParams;
    if (startfield) {
      this.startField = startfield;
    }
    if (endfield) {
      this.endField = endfield;
    }
    if (groupcolumnfield) {
      this.groupColumnField = groupcolumnfield;
    }
    if (attendcodelisttag) {
      this.attendCodeListTag = attendcodelisttag;
    }
    // await this.loadAttendCodeList();
  }

  protected initState(): void {
    super.initState();
    this.state.customColumns = [];
  }

  /**
   * @description 加载考勤代码表
   * @returns {*}  {Promise<readonly}
   * @memberof CheckinMonthGridController
   */
  async loadAttendCodeList(): Promise<readonly CodeListItem[] | undefined> {
    const app = ibiz.hub.getApp(this.context.srfappid);
    const dataItems = await app.codeList.get(
      this.attendCodeListTag,
      this.context,
      this.params,
    );
    this.attendanceTypes = dataItems;
    return dataItems;
  }

  protected async initMonthColumns(resultParams: IData): Promise<void> {
    if (!this.model.degridColumns || !this.model.degridDataItems) {
      return;
    }
    this.state.isLoaded = false;
    this.state.customColumns = [];
    const { [this.startField]: startValue, [this.endField]: endValue } =
      resultParams;
    if (!startValue || !endValue) {
      return;
    }
    const templateColumn = this.model.degridColumns.find(
      (column: IData) => column.codeName === 'template',
    );
    const start = dayjs(startValue);
    const end = dayjs(endValue);
    const startDay = start.date();
    const endDay = end.date();
    for (let i = startDay; i <= endDay; i++) {
      const targetDate = dayjs(`${start.year()}-${start.month() + 1}-${i}`);
      const targetDay = targetDate.day();
      const filedName = targetDate.format('YYYY-MM-DD');
      const column = {
        aggMode: 'NONE',
        align: templateColumn?.align,
        appDEFieldId: filedName,
        appId: this.model.appId,
        caption: `${filedName}\n${this.weekDays[targetDay]}`,
        codeName: filedName,
        columnType: 'DEFGRIDCOLUMN',
        dataItemName: filedName,
        enableSort: false,
        id: filedName,
        enableLinkView: (templateColumn as IDEGridFieldColumn)?.enableLinkView,
        linkAppViewId: (templateColumn as IDEGridFieldColumn)?.linkAppViewId,
        valueType: 'SIMPLE',
        minWidth: templateColumn?.width || 200,
        width: templateColumn?.width || 200,
        widthUnit: 'PX',
        userParam: {
          columnType: 'date',
          ...(templateColumn as IDEGridFieldColumn).userParam,
        },
      };
      this.state.customColumns.push(column);
      this.customColumnStates.push({
        key: column.codeName!,
        caption: column.caption!,
        hidden: true,
        hideMode: 0,
        uaColumn: column.columnType === 'UAGRIDCOLUMN',
        adaptive: column.widthUnit === 'STAR',
        columnWidth: column.width,
      });
    }
    await Promise.all(
      this.state.customColumns.map(async column =>
        this.initColumnsController(column),
      ),
    );
  }

  async getFetchParams(extraParams?: IParams): Promise<IParams> {
    const resultParams = await super.getFetchParams(extraParams);
    await this.initMonthColumns(resultParams);
    return resultParams;
  }

  async openLinkView(
    row: GridRowState,
    data: IData,
    event: MouseEvent,
    c: GridFieldColumnController,
  ): Promise<void> {
    if (!data) {
      // 当前值不存在，不继续走打开链接视图逻辑
      return;
    }
    const tempData = { ...row.data, ...data };
    const valueItem = c.model.linkValueItem || 'srfkey';
    const value = row.data[valueItem];
    if (value == null) {
      throw new ModelError(
        c.model,
        ibiz.i18n.t('runtime.controller.control.grid.pickedUpData', {
          valueItem,
        }),
      );
    }
    const { linkAppViewId } = c.model;
    if (!linkAppViewId) {
      return;
    }
    const wfContext = getWFContext(tempData);
    const tempContext = Object.assign(c.context.clone(), {
      srfkey: value,
      ...wfContext,
    });
    const tempParams = clone(c.params);
    const { context: newContext, params: newParams } = c.handlePublicParams(
      tempData,
      tempContext,
      tempParams,
    );
    const result = await ibiz.openView.verify(
      c.grid.view?.getTopView(),
      linkAppViewId,
      newContext,
      newParams,
      { event },
    );
    if (!result) {
      return;
    }

    // 打开视图
    const res: IModalData = await ibiz.commands.execute(
      OpenAppViewCommand.TAG,
      linkAppViewId,
      newContext,
      newParams,
      { event },
    );
    if (res?.ok) {
      c.grid.load();
    }
  }

  toggleCustomColumn(visible: boolean): void {
    this.customColumnStates.forEach(column => {
      column.hidden = !visible;
    });
  }
}
